package youtubeproject;

import com.google.gdata.client.*;
import com.google.gdata.client.Query.CategoryFilter;
import com.google.gdata.client.youtube.*;
import com.google.gdata.data.*;
import com.google.gdata.data.geo.impl.*;
import com.google.gdata.data.media.*;
import com.google.gdata.data.media.mediarss.*;
import com.google.gdata.data.youtube.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

/**
 *
 * @author adnan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        File dir = new File(new File("").getAbsolutePath());
        for (File file : dir.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                if (name.toLowerCase().endsWith("properties")) {
                    return true;
                } else {
                    return false;
                }
            }
        })) {

            System.out.println(file.getAbsolutePath());
            processBlogs(file);
        }
    }

    private static void process(String blogName, String developerKey, String label, String queryString, String bloggerUser, String bloggerPassword, String youtubeUser, String youtubePassword, int numberOfEntries) {
        try {
            YouTubeQuery query = new YouTubeQuery(new URL("http://gdata.youtube.com/feeds/api/videos"));
            query.setFullTextQuery(queryString);
            query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);
            query.setSafeSearch(YouTubeQuery.SafeSearch.MODERATE);
            YouTubeService service = new YouTubeService("Adnan", developerKey);
            service.setUserCredentials(youtubeUser, youtubePassword);
            VideoFeed videoFeed = service.query(query, VideoFeed.class);
            printVideoFeed(blogName, numberOfEntries, bloggerUser, bloggerPassword, label, videoFeed, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void printVideoFeed(String blogName, int numberOfEntries, String bloggerUser, String bloggerPassword, String label, VideoFeed videoFeed, boolean detailed) {
        int i = 0;
        for (VideoEntry videoEntry : videoFeed.getEntries()) {
            boolean isEntryDone = printVideoEntry(blogName, bloggerUser, bloggerPassword, label, videoEntry, detailed);
            if (isEntryDone == true) {
                i++;
            }
            if (i == numberOfEntries) {
                break;
            }
        }
    }

    public static boolean printVideoEntry(String blogName, String bloggerUser, String bloggerPassword, String label, VideoEntry videoEntry, boolean detailed) {
        System.out.println("Title: " + videoEntry.getTitle().getPlainText());
        boolean ret = false;
        if (videoEntry.isDraft()) {
            System.out.println("Video is not live");
            YtPublicationState pubState = videoEntry.getPublicationState();
            if (pubState.getState() == YtPublicationState.State.PROCESSING) {
                System.out.println("Video is still being processed.");
            } else if (pubState.getState() == YtPublicationState.State.REJECTED) {
                System.out.print("Video has been rejected because: ");
                System.out.println(pubState.getDescription());
                System.out.print("For help visit: ");
                System.out.println(pubState.getHelpUrl());
            } else if (pubState.getState() == YtPublicationState.State.FAILED) {
                System.out.print("Video failed uploading because: ");
                System.out.println(pubState.getDescription());
                System.out.print("For help visit: ");
                System.out.println(pubState.getHelpUrl());
            }
        }

        if (videoEntry.getEditLink() != null) {
            System.out.println("Video is editable by current user.");
        }

        if (detailed) {

            YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
            if (Record.getValue(blogName + "/" + mediaGroup.getVideoId()) == null) {

                System.out.println("Uploaded by: " + mediaGroup.getUploader());

                System.out.println("Video ID: " + mediaGroup.getVideoId());
                System.out.println("Description: " +
                        mediaGroup.getDescription().getPlainTextContent());

                MediaPlayer mediaPlayer = mediaGroup.getPlayer();
                System.out.println("Web Player URL: " + mediaPlayer.getUrl());

                /**************************************************************/
                System.out.println("Posting a New Record");
                Record.saveValue(blogName + "/" + mediaGroup.getVideoId(), mediaGroup.getDescription().getPlainTextContent());
                BloggerClient.postOnBlogSpot(blogName, bloggerUser, bloggerPassword, label, mediaGroup.getVideoId(), mediaGroup.getTitle().getPlainTextContent(), mediaGroup.getDescription().getPlainTextContent(),mediaGroup.getUploader());
                ret = true;
            /*************************************************************
            MediaKeywords keywords = mediaGroup.getKeywords();
            
            System.out.print("Keywords: ");
            for (String keyword : keywords.getKeywords()) {
            System.out.print(keyword + ",");
            }
            
            GeoRssWhere location = videoEntry.getGeoCoordinates();
            if (location != null) {
            System.out.println("Latitude: " + location.getLatitude());
            System.out.println("Longitude: " + location.getLongitude());
            }
            
            Rating rating = videoEntry.getRating();
            if (rating != null) {
            System.out.println("Average rating: " + rating.getAverage());
            }
            
            YtStatistics stats = videoEntry.getStatistics();
            if (stats != null) {
            System.out.println("View count: " + stats.getViewCount());
            }
            System.out.println();
            
            System.out.println("\tThumbnails:");
            for (MediaThumbnail mediaThumbnail : mediaGroup.getThumbnails()) {
            System.out.println("\t\tThumbnail URL: " + mediaThumbnail.getUrl());
            System.out.println("\t\tThumbnail Time Index: " +
            mediaThumbnail.getTime());
            System.out.println();
            }
            
            System.out.println("\tMedia:");
            for (YouTubeMediaContent mediaContent : mediaGroup.getYouTubeContents()) {
            System.out.println("\t\tMedia Location: " + mediaContent.getUrl());
            System.out.println("\t\tMedia Type: " + mediaContent.getType());
            System.out.println("\t\tDuration: " + mediaContent.getDuration());
            System.out.println();
            }
            
            for (YouTubeMediaRating mediaRating : mediaGroup.getYouTubeRatings()) {
            System.out.println("Video restricted in the following countries: " +
            mediaRating.getCountries().toString());
            }
             */
            } else {
                System.out.println("Skipping Entry " + mediaGroup.getDescription().getPlainTextContent());
            }

        }
        return ret;
    }

    private static void processBlogs(File file) throws IOException, FileNotFoundException {

        Properties p = new Properties();
        p.load(new FileInputStream(file));
        String bloggerUser = p.getProperty("bloggerUser");
        String bloggerPassword = p.getProperty("bloggerPassword");
        String youtubeUser = p.getProperty("youtubeUser");
        String youtubePassword = p.getProperty("youtubePassword");
        String developerKey = p.getProperty("developerKey");
        String blogName = p.getProperty("blogname");
        System.out.println(blogName);
        System.out.println(bloggerUser);
        System.out.println(youtubeUser);

        for (Object o : p.keySet()) {
            String key = (String) o;
            if (key.toLowerCase().contains("stream")) {
                String value = p.getProperty(key);
                String page = value.split(",")[0].trim();
                String search = value.split(",")[1].trim();
                process(blogName, developerKey, page, search, bloggerUser, bloggerPassword, youtubeUser, youtubePassword, 5);
            }
        }
    }
}
